import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository  } from 'typeorm'
import { ModelEntity } from '../entity/model.entity';
import { ItemEntity } from '../entity/item.entity';

/**
 * 描述
 */
@Provide()
export class ApiService  {
  @InjectEntityModel(ModelEntity)
  ModelModel: Repository<ModelEntity>;
  @InjectEntityModel(ItemEntity)
  ItemModel: Repository<ItemEntity>;

  /**
   * 描述
   */
  async getmodel(id,page=1,pageSize=10) {
    console.log( "接受到的",id,page,pageSize);
    
    if(id == 2 ){
//  返回新闻列表  数据过多

    let result1 = await  this.ModelModel
    .createQueryBuilder('model')
    .where({ Pid:id})
    .orWhere({ id:id })
    .getMany()
   for(let i = 0 ;i<result1.length;i++){
      if(result1[i].Pid){
        (result1[i] as any).item = await this.ItemModel
        .createQueryBuilder("item")
        .where({ Pid: result1[i].id }) // 假设有一个字段指向 model
        .skip((page - 1) * pageSize) // 跳过的记录数
        .take(pageSize) // 获取的记录数
        .getManyAndCount();
      }
   }
   return  result1

    }else{
      return await this.ModelModel
      .createQueryBuilder('model')
      .leftJoinAndSelect("model.item","item")
      .where({ Pid:id})
      .orWhere({ id:id })
      .orderBy("model.UpdateDate", "ASC")
      .getMany()
    }

   

  }
  async getdetail(id,detailid) {
    console.log( "接受到的",id,detailid);
    

      return await this.ModelModel
      .createQueryBuilder('model')
      .leftJoinAndSelect("model.item","item","item.id ="+detailid)
      .where({ Pid:id})
      .orWhere({ id:id })
      .getMany()
    

   

  }

  async getindex(){
    // 查询新闻前6条数据
    let find1 = this.ItemModel
    .createQueryBuilder('item')
    .where({ Pid:9 })
    .orderBy("item.CreateDate",'DESC')
    .take(6)
    let find2 =this.ItemModel
    .createQueryBuilder('item')
    .where({ Pid:10 })
    .orderBy("item.CreateDate",'DESC')
    .take(6)
    let find3 =this.ItemModel
    .createQueryBuilder('item')
    .where({ Pid:7 })
    .orderBy("item.CreateDate",'DESC')
 
    
    let [ a, b,c ] =  await Promise.all(  [find1.getMany(),find2.getMany(),find3.getMany()] )
    return { 
        new1:a,
        new2:b,
        card:c
    }
  }
}
